go to index

Random Forests

read time 4 min read
Kaggle Intro Machine Learning

Random Forests

Introduction

决策树留给你一个艰难的决定。有很多叶子的深树会过拟合,因为每个预测都是来自叶子附近的少数房屋的历史数据。但是一棵叶子很少的浅树会表现得很差,因为它无法在原始数据中捕捉到尽可能多的区别。

即使是今天最复杂的建模技术也面临着欠拟合和过拟合之间的紧张关系。但是,许多模型都有聪明的想法,可以带来更好的性能。我们将以 Random Forests(随机森林) 为例。

随机森林使用许多树,它通过平均每个组成树的预测来进行预测。它通常比单一决策树具有更好的预测准确性,并且在默认参数下工作得很好。如果您继续建模,您可以学习更多具有更好性能的模型,但是其中许多模型对获得正确的参数很敏感。

Example

您已经看过几次加载数据的代码。在数据加载结束时,我们有以下变量:

  • train_X
  • val_X
  • train_y
  • val_y
python
import pandas as pd
    
# Load data
melbourne_file_path = '../input/melbourne-housing-snapshot/melb_data.csv'
melbourne_data = pd.read_csv(melbourne_file_path) 
# Filter rows with missing values
melbourne_data = melbourne_data.dropna(axis=0)
# Choose target and features
y = melbourne_data.Price
melbourne_features = ['Rooms', 'Bathroom', 'Landsize', 'BuildingArea', 
                        'YearBuilt', 'Lattitude', 'Longtitude']
X = melbourne_data[melbourne_features]

from sklearn.model_selection import train_test_split

# split data into training and validation data, for both features and target
# The split is based on a random number generator. Supplying a numeric value to
# the random_state argument guarantees we get the same split every time we
# run this script.
train_X, val_X, train_y, val_y = train_test_split(X, y,random_state = 0)

我们构建了一个随机森林模型,类似于我们在scikit-learn中构建决策树的方式——这次使用RandomForestRegressor类而不是DecisionTreeRegressor。

python
from sklearn.ensemble import RandomForestRegressor
from sklearn.metrics import mean_absolute_error

forest_model = RandomForestRegressor(random_state=1)
forest_model.fit(train_X, train_y)
melb_preds = forest_model.predict(val_X)
print(mean_absolute_error(val_y, melb_preds))
plaintext
191669.7536453626

Conclusion

可能还有进一步改进的空间,但这已经比25万的最佳决策树误差有了很大的改进。有一些参数允许你改变随机森林的性能,就像我们改变单个决策树的最大深度一样。但随机森林模型的一个最佳特征是,即使没有这种调整,它们通常也能合理地工作。

Exercise

Recap

python
# Code you have previously used to load data
import pandas as pd
from sklearn.metrics import mean_absolute_error
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeRegressor


# Path of the file to read
iowa_file_path = '../input/home-data-for-ml-course/train.csv'

home_data = pd.read_csv(iowa_file_path)
# Create target object and call it y
y = home_data.SalePrice
# Create X
features = ['LotArea', 'YearBuilt', '1stFlrSF', '2ndFlrSF', 'FullBath', 'BedroomAbvGr', 'TotRmsAbvGrd']
X = home_data[features]

# Split into validation and training data
train_X, val_X, train_y, val_y = train_test_split(X, y, random_state=1)

# Specify Model
iowa_model = DecisionTreeRegressor(random_state=1)
# Fit Model
iowa_model.fit(train_X, train_y)

# Make validation predictions and calculate mean absolute error
val_predictions = iowa_model.predict(val_X)
val_mae = mean_absolute_error(val_predictions, val_y)
print("Validation MAE when not specifying max_leaf_nodes: {:,.0f}".format(val_mae))

# Using best value for max_leaf_nodes
iowa_model = DecisionTreeRegressor(max_leaf_nodes=100, random_state=1)
iowa_model.fit(train_X, train_y)
val_predictions = iowa_model.predict(val_X)
val_mae = mean_absolute_error(val_predictions, val_y)
print("Validation MAE for best value of max_leaf_nodes: {:,.0f}".format(val_mae))


# Set up code checking
from learntools.core import binder
binder.bind(globals())
from learntools.machine_learning.ex6 import *
print("\nSetup complete")

Step 1: Use a Random Forest

python
from sklearn.ensemble import RandomForestRegressor

# Define the model. Set random_state to 1
rf_model = RandomForestRegressor(random_state=1)

# fit your model
rf_model = rf_model.fit(train_X,train_y)
model_pred = rf_model.predict(val_X)
# Calculate the mean absolute error of your Random Forest model on the validation data
rf_val_mae = mean_absolute_error(val_y,model_pred)

print("Validation MAE for Random Forest Model: {}".format(rf_val_mae))

# Check your answer
step_1.check()